/**
 * 
 */
package rs.networx.dao;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.Query;

import rs.networx.entity.FriendRequest;
import rs.networx.entity.Person;

/**
 * @author SPECULEES
 *
 */
@Stateless									
@Local(FriendRequestDao.class)              
public class FriendRequestDaoBean extends GenericDaoBean<FriendRequest, Integer> implements FriendRequestDao {

	@EJB
	PersonDao personDao;

	@SuppressWarnings("unchecked")
	@Override
	public Integer getfriendRequestsCountForLoggedUser(Person loggedUser) {
System.out.println("LOADING: getfriendRequestsCountForLoggedUser");
		
		Query q = em.createQuery("SELECT fr FROM FriendRequest fr WHERE fr.requestTo=:loggedUser and fr.status=1");
		
		q.setParameter("loggedUser", loggedUser);
		List<FriendRequest> results = q.getResultList();

		if (results.size() == 0) {
			return new Integer(0);
		}
		System.out.println("Loaded: " + results.size() + " friend requests");
		return new Integer(results.size());
	}
	
	public List<FriendRequest> getAllPersonsISentFriendRequests(Person loggedUser) {
		Query q = em.createQuery("SELECT fr FROM FriendRequest fr WHERE fr.requestFrom=:loggedUser");

		q.setParameter("loggedUser", loggedUser);
		@SuppressWarnings("unchecked")
		List<FriendRequest> results = q.getResultList();

		if (results.size() == 0) {
			return null;
		}
		return results;
	}

	@Override
	public boolean checkIfISentFriendRequest(Person loggedUser, Person personToCheck) {
		boolean methodResult = false;
		Integer loggedUserID;
		List<FriendRequest> results = getAllPersonsISentFriendRequests(loggedUser);
		
		/*Query q = em.createQuery("SELECT fr FROM FriendRequest fr WHERE fr.requestFrom=:loggedUser");
		q.setParameter("loggedUser", loggedUser);*/
		if(results == null || results.size() == 0){
			return false;
		}
		for(int i = 0; i < results.size(); i++){
			loggedUserID = results.get(i).getRequestFrom().getId();
			System.out.println("loggedPersonID" + loggedUserID);
			if(loggedUserID.equals(personToCheck.getId())){
				methodResult = true;
				break;
			}else{
				continue;
			}
		}	
		return methodResult;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FriendRequest> getAllFriendRequestsForLoggedUser(
			Person loggedUser) {
System.out.println("Loaded getAllFriendRequestsForLoggedUser...");
		
		Query q = em.createQuery("SELECT fr FROM FriendRequest fr WHERE fr.requestTo=:loggedUser and fr.status=1");
		
		q.setParameter("loggedUser", loggedUser);
		List<FriendRequest> results = q.getResultList();

		if (results.size() == 0) {
			System.out.println("size is null");
			return null;
		}
		System.out.println("Loaded: " + results.size() + " friend requests");
		return results;
	}
	}

